//
//  QVerifyWebViewController.m
//  QWeiboSDK4iOSDemo
//
//  Created   on 11-1-14.
//   
//

#import "QVerifyWebViewController.h"
#import "QWeiboSyncApi.h"
#import "NSURL+QAdditions.h"


#define VERIFY_URL @"http://open.t.qq.com/cgi-bin/authorize?oauth_token="

@implementation QVerifyWebViewController

@synthesize delegate, appKey, appSecret, tokenKey, tokenSecret;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}

- (id)initwithTokenKey:(NSString*)_tokenKey
           TokenSecret:(NSString*)_tokenSecret 
                appKey:(NSString*)_appKey
             appSecret:(NSString*)_appSecret
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.tokenKey = _tokenKey;
        self.tokenSecret = _tokenSecret;
        self.appKey = _appKey;
        self.appSecret = _appSecret;
        UINavigationBar *navigateBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 43)];
        [self.view addSubview:navigateBar];
        UINavigationItem *navItem = [[[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"腾讯微博", nil)] autorelease];
        UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(backBtnTap)];
        navItem.leftBarButtonItem = [backBtn autorelease];
        [navigateBar pushNavigationItem:navItem animated:YES];
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	mWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 43.0f, 320.0f, 436.0f)];
	mWebView.delegate = self;
	[self.view addSubview:mWebView];
    
	NSString *url = [NSString stringWithFormat:@"%@%@", VERIFY_URL, tokenKey];
	NSURL *requestUrl = [NSURL URLWithString:url];
	NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
	[mWebView loadRequest:request];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    delegate = nil;
    [mWebView   release];
    [appKey     release];
    [appSecret  release];
    [tokenKey   release];
    [tokenSecret    release];
    [super  dealloc];
}

#pragma mark -
#pragma mark private methods

-(NSString*) valueForKey:(NSString *)key ofQuery:(NSString*)query
{
	NSArray *pairs = [query componentsSeparatedByString:@"&"];
	for(NSString *aPair in pairs){
		NSArray *keyAndValue = [aPair componentsSeparatedByString:@"="];
		if([keyAndValue count] != 2) continue;
		if([[keyAndValue objectAtIndex:0] isEqualToString:key]){
			return [keyAndValue objectAtIndex:1];
		}
	}
	return nil;
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
	
	NSString *query = [[request URL] query];
	NSString *verifier = [self valueForKey:@"oauth_verifier" ofQuery:query];
	
	if (verifier && ![verifier isEqualToString:@""]) {
		QWeiboSyncApi *api = [[[QWeiboSyncApi alloc] init] autorelease];
		NSString *retString = [api getAccessTokenWithConsumerKey:appKey 
												  consumerSecret:appSecret 
												 requestTokenKey:tokenKey 
											  requestTokenSecret:tokenSecret 
														  verify:verifier];
		NSLog(@"\nget access token:%@", retString);
		NSDictionary *params = [NSURL parseURLQueryString:retString];
        tokenKey = [params objectForKey:@"oauth_token"];
        tokenSecret = [params objectForKey:@"oauth_token_secret"];
        if ([delegate respondsToSelector:@selector(controller:tokenKey:tokenSecret:appKey:appSecret:)]) {
            [delegate controller:self
                        tokenKey:tokenKey
                     tokenSecret:tokenSecret
                          appKey:appKey
                       appSecret:appSecret];
        }
		[self dismissModalViewControllerAnimated:YES];
		return NO;
	}
	
	return YES;
}

- (void)backBtnTap
{
    [self dismissModalViewControllerAnimated:YES];
}

@end
